/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mrp.persistencia.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import mrp.persistencia.entity.Materiaprima;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import mrp.beans.util.EntityManagerUtil;
import mrp.persistencia.controller.exceptions.IllegalOrphanException;
import mrp.persistencia.controller.exceptions.NonexistentEntityException;
import mrp.persistencia.controller.exceptions.PreexistingEntityException;
import mrp.persistencia.controller.exceptions.RollbackFailureException;
import mrp.persistencia.entity.Insumo;

/**
 *
 * @author root
 */
public class InsumoJpaController implements Serializable {

    public InsumoJpaController() {
        
        this.emf = EntityManagerUtil.getEntityManagerFactory();
    }

    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Insumo insumo) throws PreexistingEntityException, RollbackFailureException, Exception {
//        if (insumo.getMateriaprimaList() == null) {
//            insumo.setMateriaprimaList(new ArrayList<Materiaprima>());
//        }
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
//            List<Materiaprima> attachedMateriaprimaList = new ArrayList<Materiaprima>();
//            for (Materiaprima materiaprimaListMateriaprimaToAttach : insumo.getMateriaprimaList()) {
//                materiaprimaListMateriaprimaToAttach = em.getReference(materiaprimaListMateriaprimaToAttach.getClass(), materiaprimaListMateriaprimaToAttach.getCodmateriaprima());
//                attachedMateriaprimaList.add(materiaprimaListMateriaprimaToAttach);
//            }
//            insumo.setMateriaprimaList(attachedMateriaprimaList);
            em.persist(insumo);
//            for (Materiaprima materiaprimaListMateriaprima : insumo.getMateriaprimaList()) {
//                Insumo oldInsumoFkOfMateriaprimaListMateriaprima = materiaprimaListMateriaprima.getInsumoFk();
//                materiaprimaListMateriaprima.setInsumoFk(insumo);
//                materiaprimaListMateriaprima = em.merge(materiaprimaListMateriaprima);
//                if (oldInsumoFkOfMateriaprimaListMateriaprima != null) {
//                    oldInsumoFkOfMateriaprimaListMateriaprima.getMateriaprimaList().remove(materiaprimaListMateriaprima);
//                    oldInsumoFkOfMateriaprimaListMateriaprima = em.merge(oldInsumoFkOfMateriaprimaListMateriaprima);
//                }
//            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findInsumo(insumo.getCodinsumo()) != null) {
                throw new PreexistingEntityException("Insumo " + insumo + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Insumo insumo) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Insumo persistentInsumo = em.find(Insumo.class, insumo.getCodinsumo());
//            List<Materiaprima> materiaprimaListOld = persistentInsumo.getMateriaprimaList();
//            List<Materiaprima> materiaprimaListNew = insumo.getMateriaprimaList();
//            List<String> illegalOrphanMessages = null;
//            for (Materiaprima materiaprimaListOldMateriaprima : materiaprimaListOld) {
//                if (!materiaprimaListNew.contains(materiaprimaListOldMateriaprima)) {
//                    if (illegalOrphanMessages == null) {
//                        illegalOrphanMessages = new ArrayList<String>();
//                    }
//                    illegalOrphanMessages.add("You must retain Materiaprima " + materiaprimaListOldMateriaprima + " since its insumoFk field is not nullable.");
//                }
//            }
//            if (illegalOrphanMessages != null) {
//                throw new IllegalOrphanException(illegalOrphanMessages);
//            }
//            List<Materiaprima> attachedMateriaprimaListNew = new ArrayList<Materiaprima>();
//            for (Materiaprima materiaprimaListNewMateriaprimaToAttach : materiaprimaListNew) {
//                materiaprimaListNewMateriaprimaToAttach = em.getReference(materiaprimaListNewMateriaprimaToAttach.getClass(), materiaprimaListNewMateriaprimaToAttach.getCodmateriaprima());
//                attachedMateriaprimaListNew.add(materiaprimaListNewMateriaprimaToAttach);
//            }
//            materiaprimaListNew = attachedMateriaprimaListNew;
//            insumo.setMateriaprimaList(materiaprimaListNew);
//            insumo = em.merge(insumo);
//            for (Materiaprima materiaprimaListNewMateriaprima : materiaprimaListNew) {
//                if (!materiaprimaListOld.contains(materiaprimaListNewMateriaprima)) {
//                    Insumo oldInsumoFkOfMateriaprimaListNewMateriaprima = materiaprimaListNewMateriaprima.getInsumoFk();
//                    materiaprimaListNewMateriaprima.setInsumoFk(insumo);
//                    materiaprimaListNewMateriaprima = em.merge(materiaprimaListNewMateriaprima);
//                    if (oldInsumoFkOfMateriaprimaListNewMateriaprima != null && !oldInsumoFkOfMateriaprimaListNewMateriaprima.equals(insumo)) {
//                        oldInsumoFkOfMateriaprimaListNewMateriaprima.getMateriaprimaList().remove(materiaprimaListNewMateriaprima);
//                        oldInsumoFkOfMateriaprimaListNewMateriaprima = em.merge(oldInsumoFkOfMateriaprimaListNewMateriaprima);
//                    }
//                }
//            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = insumo.getCodinsumo();
                if (findInsumo(id) == null) {
                    throw new NonexistentEntityException("The insumo with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            
            em = getEntityManager();
            em.getTransaction().begin();
            Insumo insumo;
            try {
                insumo = em.getReference(Insumo.class, id);
                insumo.getCodinsumo();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The insumo with id " + id + " no longer exists.", enfe);
            }
//            List<String> illegalOrphanMessages = null;
//            List<Materiaprima> materiaprimaListOrphanCheck = insumo.getMateriaprimaList();
//            for (Materiaprima materiaprimaListOrphanCheckMateriaprima : materiaprimaListOrphanCheck) {
//                if (illegalOrphanMessages == null) {
//                    illegalOrphanMessages = new ArrayList<String>();
//                }
//                illegalOrphanMessages.add("This Insumo (" + insumo + ") cannot be destroyed since the Materiaprima " + materiaprimaListOrphanCheckMateriaprima + " in its materiaprimaList field has a non-nullable insumoFk field.");
//            }
//            if (illegalOrphanMessages != null) {
//                throw new IllegalOrphanException(illegalOrphanMessages);
//            }
            em.remove(insumo);
            em.getTransaction().commit();
        } catch (Exception ex) {
            try {
                em.getTransaction().rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Insumo> findInsumoEntities() {
        return findInsumoEntities(true, -1, -1);
    }

    public List<Insumo> findInsumoEntities(int maxResults, int firstResult) {
        return findInsumoEntities(false, maxResults, firstResult);
    }

    private List<Insumo> findInsumoEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Insumo.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Insumo findInsumo(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Insumo.class, id);
        } finally {
            em.close();
        }
    }

    public int getInsumoCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Insumo> rt = cq.from(Insumo.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
  public List<Insumo> findInsumoOrderBy(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT o FROM Insumo o order by o.codinsumo");
             if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }           
            return q.getResultList();
        } 
        catch(Exception e)
        {e.printStackTrace();}
        finally {
            em.close();
        }
        return null;
    }  
}
